package com.franklin.java.api.ui.jpanel.checkbox;

import com.franklin.plugins.common.utils.DataCheckUtils;

import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * @author Franklin
 * @since 2021/9/1 10:18
 */
public class MultipleForOneCheckBox extends MultipleCheckBox{

    public MultipleForOneCheckBox(Collection<String> itemList,String selectedItem) {
        super(itemList, Collections.singleton(selectedItem));
        init();
    }

    private void init(){
        this.checkBoxList.forEach(checkBox -> {
            checkBox.addActionListener(e -> {
                if (checkBox.isSelected()){
                    this.checkBoxList.forEach(other -> {
                        if (!other.equals(checkBox)){
                            other.setSelected(false);
                        }
                    });
                }else if (DataCheckUtils.isEmpty(getSelectItem())){
                    checkBox.setSelected(true);
                }
            });
        });
    }

    public String getSelectItem(){
        List<String> selectItems = super.selectItems();
        if (DataCheckUtils.isEmpty(selectItems)){
            return "";
        }
        return selectItems.get(0);
    }
}
